package com.study.heartBeat;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: NettyHeartBeatServer
 * @Description:
 * @Date 2024/04/30 11:00
 * @Author songshaoqiu
 **/
public class NettyHeartBeatServer {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
                        /**
                         * IdleStateHandler处理器会在服务端 发先有超过 3秒没有发生读操作的话 会触发超时事件
                         * 会创建出IdleStateEvent对象，将该对象交由下一个Handler
                         */
                        pipeline.addLast(new IdleStateHandler(100,0,0, TimeUnit.SECONDS));
                        //HeartbeatServerHandler 必须重写userEventTriggered方法，用来做具体的超时的业务处理
                        pipeline.addLast(new NettyHeartbeatServerHandler());

                    }
                });
        ChannelFuture channelFuture = serverBootstrap.bind(9090);
        channelFuture.sync();
        //只要服务没关闭。该方法会一直阻塞
        channelFuture.channel().closeFuture().sync();
        System.out.println("netty 服务关闭--------->  执行 bind.channel().closeFuture().sync();");
    }
}
